﻿using Microsoft.Practices.Unity.InterceptionExtension;
using SalesPages.EntityFrameworkRepository;
using SalesPages.EntityFrameworkRepository.Repository;
using SalesPages.Infrastructure.IRepository;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity.Validation;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace SalesPages.Behavior
{
   
    public class UnitOfWorkInterceptionBehaviorBase : IInterceptionBehavior
    {
        public IMethodReturn Invoke(
           IMethodInvocation input,
           GetNextInterceptionBehaviorDelegate getNext)
        {
            IMethodReturn retvalue;

            if (EFUnitOfWork.Current != null || !UnitOfWorkHelper.IsDBConnectionRequired(input.MethodBase))
            {
                //retvalue = CacheBehavior.ReturnCacheValue(input, getNext);
                //retvalue = retvalue == null ? getNext()(input, getNext) : retvalue;
                retvalue = getNext()(input, getNext);
                return retvalue;
            }

            try
            {
                EFUnitOfWork.Current = 
                    new Lazy<EFUnitOfWork>(()=> CreateUnitOfWork(),
                    LazyThreadSafetyMode.PublicationOnly);

                var isolationLevel = IsolationLevel.ReadUncommitted;

                if (UnitOfWorkHelper.NeedTransaction(input.MethodBase))
                {
                    isolationLevel = IsolationLevel.ReadCommitted;
                }

                EFUnitOfWork.Current.Value.BeginTransaction(isolationLevel);

                try
                {
                    retvalue = getNext()(input, getNext);
                    EFUnitOfWork.Current.Value.Commit();
                }
                catch (Exception ex)
                {
                    if (ex is DbEntityValidationException)
                        ex = ex as DbEntityValidationException;

                    try
                    {
                        EFUnitOfWork.Current.Value.Rollback();
                    }
                    catch
                    {
                    }

                    throw new Exception("方法" + input.MethodBase.Name + "执行记录： " + ex.ToString());
                }
            }
            catch (Exception ex)
            {

                throw new Exception("方法" + input.MethodBase.Name + "执行记录： " + ex.ToString());
            }
            finally
            {
                EFUnitOfWork.Current.Value.Context.Dispose();
                EFUnitOfWork.Current = null;
            }

            return retvalue;
        }

        public IEnumerable<Type> GetRequiredInterfaces()
        {
            return Type.EmptyTypes;
        }

        public bool WillExecute
        {
            get { return true; }
        }

        protected virtual EFUnitOfWork CreateUnitOfWork()
        {
            return new EFUnitOfWork(new ET_EnglishFirstContext());
        }
    }
}
